package com.CmJava.Dubbo.provider.register.remoteRegister;




import java.io.*;
import java.util.*;

public class RemoteRegister {
    private static Map<String, List<URL>> map=new HashMap<>();

    public static void register(String serviceName,URL serviceUrl){
        if (map.containsKey(serviceName)){
            List<URL> urls = map.get(serviceName);
            urls.add(serviceUrl);
            map.put(serviceName,urls);
        }else {
            List<URL> urls = new ArrayList<>();
            urls.add(serviceUrl);
            map.put(serviceName,urls);
        }

        //因为两个进程读取不到同一个map，这里取巧存成文件
        saveFile();
    }

    private static void saveFile() {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("./tempDubbo.txt");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(map);

            objectOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream!=null && objectOutputStream!=null){
                try {
                    fileOutputStream.close();
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static URL getInterfaceUrl(String serviceName){
        getFile();

        if (map.containsKey(serviceName)){
            List<URL> urls = map.get(serviceName);
            //随机分配一个url
            return urls.get(new Random().nextInt(urls.size()));
        }

        return null;
    }

    private static void getFile() {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            fileInputStream = new FileInputStream("./tempDubbo.txt");
            objectInputStream = new ObjectInputStream(fileInputStream);
            map= (Map<String, List<URL>>) objectInputStream.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream!=null && objectInputStream!=null){
                try {
                    fileInputStream.close();
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
